<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <title>设备消息监控</title>
    <style>
        html, body {
            height: 100%;
            margin: 0;
            background-color: #3C3F41;
        }

        table {
            width: 100%;
            table-layout: fixed;
            border-collapse: collapse;
        }

        td {
            height: inherit;
            border: 1px solid #555;
        }

        select {
            width: 210px;
            height: 35px;
            display: block;
            margin: 0 auto 5px auto;
            color: #BABABA;
            font-size: 16px;
            padding: 2px;
            border: 1px solid #646464;
            background-color: #414141;
        }

        button {
            width: 90px;
            color: #BABABA;
            font-size: 18px;
            border: 1px solid #4C708C;
            background-color: #365880;
        }

        button:active {
            color: #EEE;
            border: 1px solid #6B96B4;
        }

        p {
            color: #BABABA;
            text-align: left;
            white-space: pre-wrap;
            word-wrap: break-word;
            word-break: break-all;
        }

        a {
            color: #FFF;
        }

        .cell {
            height: inherit;
            text-align: center;
            display: flex;
            flex-direction: column;
        }

        .textarea {
            height: inherit;
            overflow: auto;
            background-color: #2B2B2B;
        }

        .tool {
            padding: 10px 0 10px 0;
        }

        ::-webkit-scrollbar {
            width: 10px;
        }

        ::-webkit-scrollbar-thumb {
            background-color: #666;
        }

        ::-webkit-scrollbar-thumb:hover {
            background-color: #777;
        }
    </style>
</head>

<body>
<table id="dev_box">
    <tr>
        <td>
            <div class="cell">
                <div class="textarea" id="dev_text_[idx]"></div>
                <div class="tool">
                    <select id="dev_sel_[idx]">[option]</select>
                    <button type="button" onclick="$('dev_text_[idx]').innerHTML=''">清空</button>
                    <button type="button" onclick="unsub([idx], 'client/')">取消订阅</button>
                    <button type="button" onclick="sub([idx], 'client/')">订阅</button>
                </div>
            </div>
        </td>
    </tr>
</table>
<a href="?s=1,2" target="_blank">1*2</a>
<a href="?s=1,4" target="_blank">1*4</a>
<a href="?s=2,6" target="_blank">2*6</a>

<script src="./axios.js"></script>
<script src="//lf9-cdn-tos.bytecdntp.com/cdn/expire-1-M/stomp.js/2.3.3/stomp.min.js"></script>
<script type="text/javascript">
    const reg = new RegExp("\\[([^\\[\\]]*?)]", 'igm'); //igm是指分别用于指定区分大小写的匹配、全局匹配和多行匹配。

    const host = window.location.host;
    const domain = '//' + host;

    const stompClient = {};
    const subscriptions = {};


    const renderForm = function (data) {
        let options = '<option value="">没有可订阅的设备</option>\n';
        if (data && data.length) {
            options = '<option value="">---请选择订阅设备---</option>\n';
            options += data.map(function (device) {
                return '<option value="' + device.mobileNo + '">' + device.mobileNo + ' - ' + device.plateNo + '</option>'
            }).join('\n');
        }

        let size = [1, 1];
        const s = getQueryVariable('s');
        if (s)
            size = s.split(',');
        const row = size[0] > 3 ? 3 : size[0];
        const column = size[1] > 6 ? 6 : size[1];

        const height = Math.floor((document.documentElement.clientHeight) / row) - 1;

        const table = $('dev_box');
        const td = table.children[0].children[0].innerHTML;
        let html = '';
        let idx = 0;

        for (let i = 0; i < row; i++) {
            html += '<tr style="height: ' + height + 'px">';
            for (let j = 0; j < column; j++) {
                html += td.replace(reg, function (node, key) {
                    return ({idx: idx, option: options})[key]
                });
                ++idx;
            }
            html += '</tr>';
        }
        table.innerHTML = html;
    };

    function sub(idx, topic) {
        const select = $('dev_sel_' + idx);
        const text = $('dev_text_' + idx);

        const clientId = select.value;
        if (!clientId) {
            alert('请选择需要订阅的设备');
            return;
        }
        if (select.getAttribute('data-client-id')) {
            if (subscriptions[topic + clientId]) {
                console.warn('同一设备' + clientId + '不能重复订阅');
                return;
            }
        }

        const fn = function (data) {
            if (!data) {
                alert('设备:' + clientId + '已离线，订阅失败');
                return
            }
            const clientId = data.mobileNo;
            select.setAttribute('data-client-id', clientId);
            select.disabled = true;
            const startListener = function () {
                console.log('开始订阅车辆[' + clientId + ']实时定位....');

                subscriptions[topic + clientId] = client.subscribe(topic + clientId,
                    function (response) {
                        const c = text.scrollTop + text.offsetHeight;
                        const h = text.scrollHeight;

                        const p = document.createElement('p');
                        p.append(new Date().toISOString().replace('T', ' ').substring(0, 19) + ' ');
                        p.append(response.body);
                        text.append(p);

                        if (c >= h)
                            text.scrollTop = h;
                    }
                );
            };

            let client = stompClient[clientId];
            if (!client) {
                client = stompClient[clientId] = Stomp.client('ws://' + host + '/websocket');
                client.debug = function (res) {
                    // console.log(res)
                };
            }
            if (client.ws.readyState === 1) {
                startListener();
            } else {
                client.connect({}, function (res) {
                    console.log('websocket connect sucess!', res);
                    startListener()
                }, function (error) {
                    alert('websocket 连接失败！');
                    console.log('websocket connect failed!', error);
                })
            }
        }

        subDeviceMsg(clientId, fn);
    }

    function unsub(idx, topic) {
        const select = $('dev_sel_' + idx);
        const clientId = select.value;
        if (!clientId) {
            alert('请选择需要取消订阅的设备');
            return;
        }
        if (!select.getAttribute('data-client-id')) return;

        let subscription = subscriptions[topic + clientId];
        if (!subscription) return;

        console.log('取消订阅设备[' + clientId + ']....');
        subscription.unsubscribe();
        delete subscriptions[topic + clientId];
        select.removeAttribute('data-client-id');
        unsubDeviceMsg(clientId);
        select.disabled = false;
    }

    const subDeviceMsg = function (clientId, fn) {
        axios.request({
            url: domain + '/device/ws?sub=1&clientId=' + clientId,
            type: 'POST',
            success: function (result, status, xhr) {
                console.log(result);
                if (status === 200 && result.code === 200) {
                    fn(result.data);
                    return;
                }
                alert(result)
            }
        })
    };

    const unsubDeviceMsg = function (clientId) {
        axios.request({
            url: domain + '/device/ws?sub=0&clientId=' + clientId,
            type: 'POST',
            success: function (result, status, xhr) {
                console.log(result);
                if (status === 200 && result.code === 200) {
                    return;
                }
                alert(result);
            }
        })
    };

    const findOnlineClientId = function (fn) {
        axios.request({
            url: domain + '/device/option?_=' + Date.now(),
            success: function (result, status, xhr) {
                console.log(result);
                if (status === 200 && result.code === 200) {
                    fn(result.data);
                    return
                }
                alert(result);
            }
        })
    };

    window.onload = function () {
        findOnlineClientId(renderForm)
    }
</script>
</body>
</html>